package com.sogoodsoft.service.app;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.Query;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springside.modules.orm.Page;
import org.springside.modules.orm.PropertyFilter;

import com.sogoodsoft.dao.app.OrganizationDao;
import com.sogoodsoft.entity.app.Organization;

@Component
@Transactional
public class OrganizationService {
	@SuppressWarnings("unused")
    private static Logger logger = LoggerFactory.getLogger(OrganizationService.class);
	
	private OrganizationDao organizationDao;

	
	public void save(Organization org){
		organizationDao.save(org);
	}
	
	public void delete(Long id){
		organizationDao.delete(id);
	}
	
	@Transactional(readOnly = true)
	public Organization get(Long id){
		return organizationDao.get(id);
	}
	
	public OrganizationDao getOrganizationDao() {
		return organizationDao;
	}

	@Transactional(readOnly = true)
	@SuppressWarnings("unchecked")
	public Organization getByCode(String Code){
		Query query = this.organizationDao.createQuery("from Organization where code=?", Code);
		query.setMaxResults(1);
		List<Organization> list = (List<Organization>)query.list();
		if(list.size()>0){
			return list.get(0);
		}else{
			return null;
		}
	}
	/**
	 * 返回当前节点的所有子节点
	 * @param node
	 * @return
	 */
	@Transactional(readOnly = true)
	public List<Organization> composite(Organization node){
		List<Organization> list = new ArrayList<Organization>();
		list.add(node);
		if(node.hasChildren()){
			List<Organization> childrenList = node.getChildren();			
			for (Organization children : childrenList) {
				list.addAll(composite(children));
			}

		}
		return list;
	}
	
	/**
	 * 返回所有节点
	 * @return
	 */
	@Transactional(readOnly = true)
	public List<Organization> getAll(){
		Organization root = getRoot();		
		return composite(root);
	}
	
	/**
	 * 返回首节点
	 * @return
	 */
	@SuppressWarnings("rawtypes")
    @Transactional(readOnly = true)
	public Organization getRoot(){		
		Organization org = null;
		List querylist = organizationDao.createQuery("from Organization as org order by org.id asc").setMaxResults(1).list();
		if(querylist.size()!=0){
			org = (Organization)querylist.get(0);
		}
		return org;
	}
	
	@Transactional(readOnly = true)
	public Page<Organization> searchOrganization(Page<Organization> page,final List<PropertyFilter> filters){
		return organizationDao.findPage(page, filters);
	}
	
	@Autowired
	public void setOrganizationDao(OrganizationDao organizationDao) {
		this.organizationDao = organizationDao;
	}
	
	 
}
